package com.function.controller;

import com.function.domin.dto.BucketDTO;
import com.function.domin.dto.DownloadDTO;
import com.function.domin.pojo.Result;
import com.function.service.OSSService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@RestController
@Api(tags = "阿里云oss相关接口")
@RequestMapping("/oss")
public class OSSController {

    @Autowired
    private OSSService ossService;

    /**
     *创建bucket
     * @return
     */
    @ApiOperation("创建bucket")
    @PostMapping("/createBucket")
    public Result createBucket(@RequestBody BucketDTO bucketDTO){
        log.info("创建bucket: {}", bucketDTO);
        ossService.createBucket(bucketDTO);
        return Result.success();
    }

    /**
     * 删除bucket
     * @param bucketDTO
     * @return
     */
    @ApiOperation("删除bucket")
    @DeleteMapping("/deleteBucket")
    public Result deleteBucket(@RequestBody BucketDTO bucketDTO){
        log.info("删除bucket:{}", bucketDTO);
        ossService.deleteBucket(bucketDTO);
        return Result.success();
    }

    /**
     * 上传文件至阿里云oss
     * @param image
     * @return
     * @throws IOException
     */
    @PutMapping("/upload")
    @ApiOperation("上传文件至阿里云oss")
    public Result upload(MultipartFile image) throws IOException {
        log.info("文件上传：{}", image.getOriginalFilename());
        String url = ossService.upload(image);
        return Result.success(url);
    }

    /**
     * 从oss下载文件至本地
     * @param downloadDTO
     * @return
     */
    @GetMapping("/download")
    @ApiOperation("从oss下载文件至本地")
    public Result download(@RequestBody DownloadDTO downloadDTO){
        log.info("文件下载：{}", downloadDTO);
        String url = ossService.download(downloadDTO);
        return Result.success(url);
    }

}
